package linker.plugin;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.gnu.stealthp.rsslib.RSSChannel;
import org.gnu.stealthp.rsslib.RSSException;
import org.gnu.stealthp.rsslib.RSSHandler;
import org.gnu.stealthp.rsslib.RSSParser;

/**
 * 
 * @version linker 0.93
 * @author Jianfeng jianfeng.linker@gmail.com
 * 
 */
public class RssNotifier extends PluginItem implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTable table = new JTable();

	private JButton addButton = new JButton("Add");

	private JButton deleteButton = new JButton("Delete");

	private JButton refreshButton = new JButton("Refresh");

	private JButton gotitButton = new JButton("Got it");

	private RSSHandler handler = new RSSHandler();

	private DefaultTableModel tableModel;

	private Vector<URL> v = new Vector<URL>();

	private File dir = null;

	private Properties p = null;

	private String rsslist;

	public RssNotifier() {
		super("RssNotifier");
	}

	public void create() {
		Container container = getContentPane();
		container.setLayout(new BorderLayout());

		JPanel userPanel = new JPanel();
		addButton.addActionListener(this);
		userPanel.add(addButton);
		deleteButton.addActionListener(this);
		userPanel.add(deleteButton);
		refreshButton.addActionListener(this);
		userPanel.add(refreshButton);
		gotitButton.addActionListener(this);
		userPanel.add(gotitButton);
		container.add(userPanel, BorderLayout.NORTH);

		tableModel = new DefaultTableModel();
		tableModel.addColumn("Title");
		tableModel.addColumn("Last update");
		tableModel.addColumn("Status");
		tableModel.addColumn("URL");
		table.setModel(tableModel);
		table.setColumnSelectionAllowed(false);
		table.setCellSelectionEnabled(false);
		table.setRowSelectionAllowed(true);
		container.add(new JScrollPane(table), BorderLayout.CENTER);

		setWindow();
	}

	public String toString() {
		return "RssNotifier";
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == addButton) {
			String u = JOptionPane.showInputDialog("Input url");

			addUrl(u);
		} else if (e.getSource() == deleteButton) {
			int i = table.getSelectedRow();
			p.remove(tableModel.getValueAt(i, 0));
			try {
				p.store(new FileOutputStream(rsslist), "RSS list");
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			if (i >= 0) {
				tableModel.removeRow(i);
				v.remove(i);
			}

		} else if (e.getSource() == refreshButton) {
			refresh();
		} else if (e.getSource() == gotitButton) {
			int i = table.getSelectedRow();
			if (i < 0)
				return;

			table.setValueAt("", i, 2);
		}
	}

	public void refresh() {
		for (int i = 0; i < tableModel.getRowCount(); i++) {
			String u = (String) tableModel.getValueAt(i, 3);
			if (u.length() < 5)
				break;

			URL url;
			try {
				url = new URL(u);
				RSSParser.parseXmlFile(url, handler, false);
				RSSChannel ch = handler.getRSSChannel();

				if (!ch.getLastBuildDate().equals(tableModel.getValueAt(i, 1))) {
					tableModel.setValueAt("New!", i, 2);
					tableModel.setValueAt(ch.getLastBuildDate(), i, 1);
					p.put(ch.getTitle() + "update", ch.getLastBuildDate());
					p.store(new FileOutputStream(rsslist), "RSS list");

					addStringMessage(ch.getTitle() + " has new", this);
				}
			} catch (RSSException e1) {
				e1.printStackTrace();
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			} catch (FileNotFoundException e1) {
				System.out.println("Can't find file:" + rsslist.toString());
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
				continue;
			}
		}
	}

	private void addUrl(String u) {
		if (u.length() < 6)
			return;
		try {
			URL url = new URL(u);

			RSSParser.parseXmlFile(url, handler, false);
			RSSChannel ch = handler.getRSSChannel();

			v.add(url);
			Vector<String> temp = new Vector<String>();
			temp.add(ch.getTitle());
			temp.add(ch.getLastBuildDate());
			temp.add("New!");
			temp.add(u);
			tableModel.addRow(temp);

			String title = ch.getTitle();
			if (title == null)
				title = "";

			p.put(title + "update", ch.getLastBuildDate());
			p.put(title, u);
			p.store(new FileOutputStream(rsslist), "RSS list");
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (RSSException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	public void setPluginDir(final String path) {
		create();
		icon = new ImageIcon(path + fileSeparator + "icon.png");

		dir = new File(path);
		rsslist = dir.getAbsolutePath() + fileSeparator + "rsslist";

		try {
			p = new Properties();
			p.load(new FileInputStream(rsslist));
		} catch (FileNotFoundException e) {
			try {
				new File(rsslist).createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (p == null || p.isEmpty()) {
			return;
		}

		Enumeration<Object> e = p.keys();
		while (e.hasMoreElements()) {
			String u = (String) e.nextElement();
			if (u.endsWith("update"))
				continue;

			Vector<String> v = new Vector<String>();
			v.add(u);
			v.add((String) p.get(u + "update"));
			v.add("");
			v.add((String) p.get(u));
			tableModel.addRow(v);
		}

		System.out.println("Plugin RssNotifier refreshing...");
		refresh();
		System.out.println("Plugin RssNotifier refresh done");

	}

}
